<template>
    <el-card class="box-card">
        <header-template slot="header" ref="header"
                         :table-ref="tableOptions.ref"
                         :toolbar_buttons="headerOption.toolbar_buttons"
                         :toolbar_filter="headerOption.toolbar_filter"
                         :searchForm="searchForm"
                         @event="handleHeaderEvent">
            <template slot="right_search">
                <template v-if="type === 'buy'">
                    <vSelectBottom v-model="searchForm.supplier_sid" type="supplierDrawer"
                                   :options="supplierOptions" @event="getList(true)"
                                   style="width: 120px;" />
                </template>
                <template v-else-if="type === 'sale'">
                    <vSelectBottom v-model="searchForm.client_sid" type="clientsDrawer"
                                   :options="clientOptions" @event="getList(true)"
                                   style="width: 120px;" />
                </template>
                <el-select v-model="searchForm.confirm_state" class="w100" clearable
                           @change="getList(true)">
                    <el-option label="票据状态" value="" />
                    <el-option :label="type === 'buy' ? '待收' : '待开'" :value="0" />
                    <el-option :label="type === 'buy' ? '已收' : '已开'" :value="1" />
                </el-select>
                <el-select v-model="searchForm.audit_state" class="w100" clearable
                           @change="getList(true)">
                    <el-option label="审核状态" value="" />
                    <el-option label="待审核" :value="0" />
                    <el-option label="已审核" :value="1" />
                </el-select>
            </template>
        </header-template>
        <div class="card_content">
            <vxe-table-template :data="dataList" :options.sync="tableOptions"
                                @event="handleTableEvent" />
        </div>
    </el-card>
</template>

<script>
import { mapState } from "vuex";
import provide from "@common/mixins/provide";
import common from "@jxc/utils/common";
import InvoiceForm from "../dialog/InvoiceForm";

export default {
    extends: provide,
    name: "Invoice",
    props: {
        type: {
            type: String,
            default: 'buy',
        },
        orderType: {
            type: Number,
            default: null,
        },
        permission: {
            type: Object,
            default() {
                return {};
            },
        },
    },
    data() {
        const _this = this;
        return {
            supplierOptions: {
                disabled: true,
                placeholder: '供应商选择',
                bottomAction: {
                    permission: 'save_sys_supplier',
                    permissionUrl: '/sysSupplier',
                },
            },
            clientOptions: {
                disabled: false,
                placeholder: '客户选择',
                bottomAction: {
                    permission: 'save_sys_client',
                    permissionUrl: '/sysClients',
                },
            },
            searchForm: {
                order_type: _this.orderType === null ? '' : _this.orderType,
                audit_state: '',
                state: '',
                stock_info: '',
                confirm_state: '',
            },
            headerOption: {
                toolbar_buttons: [
                    {
                        id: "refresh",
                        icon: "el-icon-refresh-right",
                        show: true,
                        method: () => {
                            _this.getList();
                        },
                    },
                    {
                        id: "edit",
                        icon: "fa fa-pencil",
                        type: "success",
                        show: true,
                        permission: _this.permission.save,
                        method: () => {
                            _this.openDialog(null, 'edit');
                        },
                    },
                    {
                        id: "delete",
                        icon: "fa fa-trash-o",
                        type: "danger",
                        show: true,
                        permission: _this.permission.delete,
                        method: () => {
                            _this.deleteConfirm();
                        },
                    },
                    {
                        id: "audit",
                        label: '审核',
                        icon: "el-icon-top-right",
                        class: 'audit_btn',
                        show: true,
                        permission: _this.permission.audit,
                        method: () => {
                            _this.changeAuditState('audit');
                        },
                    },
                    {
                        id: "reAudit",
                        label: '反审',
                        icon: "el-icon-bottom-left",
                        class: 're_audit_btn',
                        show: true,
                        permission: _this.permission.reAudit,
                        method: () => {
                            _this.changeAuditState('reAudit');
                        },
                    },
                    {
                        id: "confirm",
                        label: _this.type === 'buy' ? '确认收票' : '确认开票',
                        type: 'success',
                        show: true,
                        permission: _this.permission.confirm,
                        method: () => {
                            _this.changeConfirmState(null, 'confirm');
                        },
                    },
                    {
                        id: "reConfirm",
                        label: _this.type === 'buy' ? '反确认收票' : '反确认开票',
                        type: 'warning',
                        show: true,
                        permission: _this.permission.reConfirm,
                        method: () => {
                            _this.changeConfirmState(null, 'reConfirm');
                        },
                    },
                ],
                toolbar_filter: [],
            },
            dataList: [],
            selectionList: [],
            tableOptions: {
                ref: "XdBuyOrderTable",
                container: ".xd_buy_order_container",
                multiSelect: true,
                showSummary: true,
                summaryArray: [ "amount", "un_pay_amount" ],
                rowClassName({ row }) {
                    let classes = [];
                    if (row.state !== 1) {
                        classes.push('cancel_row');
                    }
                    return classes;
                },
                columns: [],
                baseColumns: [
                    {
                        label: "审核状态",
                        prop: "audit_state",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return '已审核';
                            }
                            return '待审核';
                        },
                    },
                    {
                        label: "状态",
                        prop: "state",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.state) && row.state === 1) {
                                return '有效';
                            }
                            return '已作废';
                        },
                    },
                    {
                        label: "开票申请编号",
                        prop: "code",
                        align: "center",
                        minWidth: 160,
                        permission: [ 'sale' ],
                    },
                    {
                        label: "收票申请编号",
                        prop: "code",
                        align: "center",
                        minWidth: 160,
                        permission: [ 'buy' ],
                    },
                    {
                        label: "发票类型",
                        prop: "invoice_type",
                        align: "center",
                        minWidth: 90,
                        permission: [ 'sale', 'buy' ],
                        formatter(row) {
                            let filter = _this.invoiceTypeList.filter(item => item.value === row.invoice_type);
                            if (_this.$utils.isNotEmptyList(filter)) {
                                return filter[0].label;
                            }
                            return '';
                        },
                    },
                    {
                        label: "客户",
                        prop: "client_display",
                        align: "center",
                        permission: [ 'sale' ],
                    },
                    {
                        label: "供应商",
                        prop: "supplier_display",
                        align: "center",
                        permission: [ 'buy' ],
                    },
                    {
                        label: "金额",
                        prop: "amount",
                        align: "center",
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "票据信息",
                        prop: "invoice_info",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        minWidth: 90,
                    },
                    {
                        label: "部门",
                        prop: "sys_group_name",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "录入人",
                        prop: "creator_person_name",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "录入时间",
                        prop: "create_date",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        width: 130,
                    },
                    {
                        label: "审核人",
                        prop: "auditor_person_name",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return row.auditor_person_name;
                            }
                            return '';
                        },
                    },
                    {
                        label: "审核时间",
                        prop: "audit_date",
                        align: "center",
                        width: 130,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.audit_state) && row.audit_state === 1) {
                                return row.audit_date;
                            }
                            return '';
                        },
                    },
                    {
                        label: _this.type === 'buy' ? '确认收票人' : '确认开票人',
                        prop: "confirmer_person_name",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.confirm_state) && row.confirm_state === 1) {
                                return row.confirmer_person_name;
                            }
                            return '';
                        },
                    },
                    {
                        label: _this.type === 'buy' ? '确认收票时间' : '确认开票时间',
                        prop: "confirm_date",
                        align: "center",
                        width: 130,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.confirm_state) && row.confirm_state === 1) {
                                return row.confirm_date;
                            }
                            return '';
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: "info",
                            icon: "fa fa-info-circle",
                            type: "warning ",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "详情",
                            },
                            filter(row) {
                                return row.state === 0 || (row.state === 1 && row.audit_state === 1);
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'detail');
                            },
                        },
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            type: "success",
                            size: "mini",
                            show: true,
                            permission: _this.permission.save,
                            tooltip: {
                                content: "编辑",
                            },
                            filter(row) {
                                return row.state === 1 && row.audit_state === 0;
                            },
                            method: (index, row) => {
                                _this.openDialog(row, 'edit');
                            },
                        },
                        {
                            id: "cancel",
                            label: _this.type === 'buy' ? '确认收票' : '确认开票',
                            type: "success",
                            size: "mini",
                            show: true,
                            permission: _this.permission.confirm,
                            filter(row) {
                                return row.state === 1 && row.audit_state === 1 && row.confirm_state !== 1;
                            },
                            method: (index, row) => {
                                _this.changeConfirmState(row, 'confirm');
                            },
                        },
                        {
                            id: "invoice",
                            label: _this.type === 'buy' ? '反确认收票' : '反确认开票',
                            type: "warning ",
                            size: "mini",
                            show: true,
                            permission: _this.permission.reConfirm,
                            filter(row) {
                                return row.state === 1 && row.audit_state === 1 && row.confirm_state === 1;
                            },
                            method: (index, row) => {
                                _this.changeConfirmState(row, 'reConfirm');
                            },
                        },
                        {
                            id: "del",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            size: "mini",
                            show: true,
                            permission: _this.permission.delete,
                            tooltip: {
                                content: "删除",
                            },
                            filter(row) {
                                return row.state === 1;
                            },
                            method: (index, row) => {
                                _this.deleteConfirm(row);
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
        };
    },
    computed: {
        ...mapState('xiongda', [ 'invoiceTypeList' ]),
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            this.initTableOptions();
            this.getList(true);
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = columns.filter(item => item.permission.indexOf(_this.type) !== -1);
            if (_this.orderType === 1) {
                columns = columns.filter(item => item.prop !== 'un_pay_amount');
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns,
            });
        },
        handleHeaderEvent(event) {
            const _this = this;
            _this.searchForm = $.extend({}, _this.searchForm, event.searchForm);
            if (event.type === 'search') {
                _this.getList(true)
            } else if (event.type === 'refresh') {
                _this.getList(true)
            }
        },
        getList(query) {
            const _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            queryData.type = _this.type;
            let url = _this.$api.API_FindJxcInvoices4Sale;
            if (_this.type === 'buy') {
                url = _this.$api.API_FindJxcInvoices4Buy;
            }
            _this.fetchData(url, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        async openDialog(row, type) {
            const _this = this;
            let data = await common.checkRow(_this, {
                type, row,
                selectionList: _this.selectionList,
                label: `${ _this.type === 'sale' ? '开' : '收' }票申请`,
            });
            if (!data) {
                return;
            }
            if (type === 'add') {
                data = {
                    type: _this.type,
                };
            }
            let detail = type === 'detail' || data.audit_state === 1;
            _this.$dialog({
                title: `${ _this.type === 'sale' ? '开' : '收' }票申请`,
                width: '1000px',
                component: {
                    value: InvoiceForm,
                    props: {
                        type: data.type,
                        row: data,
                        invoiceTypeList: _this.invoiceTypeList,
                        detail,
                    },
                },
                hideConfirmBtn: detail,
                confirmed() {
                    _this.getList();
                },
            });
        },
        async deleteConfirm(row) {
            const _this = this;
            let list = await common.checkRow(_this, {
                type: 'delete', row,
                selectionList: _this.selectionList,
                label: `${ _this.type === 'sale' ? '开' : '收' }票申请`,
            });
            if (!list) {
                return;
            }
            _this.fetchData(_this.$api.API_DeleteJxcInvoices, {
                sids: list.map(item => item.sid),
            }).then(() => {
                _this.$message.success('删除成功！');
                _this.getList();
            }).catch(() => {
            });
        },
        async changeAuditState(type) {
            const _this = this;
            let list = await common.checkRow(_this, {
                type,
                selectionList: _this.selectionList,
                label: `${ _this.type === 'sale' ? '开' : '收' }票申请`,
                auditCheck: type === 'audit' ? 1 : 0,
            });
            if (!list) {
                return;
            }
            if (type === 'audit' && _this.selectionList.length === 1) {
                _this.openAuditDialog(_this.selectionList[0]);
                return;
            }
            _this.fetchData(_this.$api.API_ChangeJxcInvoiceAuditState, {
                sid_list: list.map(item => item.sid),
                state: type === 'audit' ? 1 : -1,
            }).then(() => {
                _this.$message.success(`${ type === 'audit' ? '审核' : '反审' }成功！`);
                _this.getList();
            }).catch(() => {
            });
        },
        async changeConfirmState(row, type) {
            const _this = this;
            let label = `${ _this.type === 'sale' ? '开' : '收' }票申请`;
            let list = await common.checkRow(_this, {
                type, row,
                selectionList: _this.selectionList,
                label,
                auditCheck: 0,
            });
            if (!list) {
                return;
            }
            let filter = list.filter(item => item.confirm_state === 1);
            if (type === 'reConfirm') {
                filter = list.filter(item => item.confirm_state !== 1);
            }
            if (_this.$utils.isNotEmptyList(filter)) {
                let codeList = list.map(item => item.code);
                if (type === 'reConfirm') {
                    _this.$message.error(`${ label }：${ codeList.join('、') } 未确认，无法反确认`);
                } else {
                    _this.$message.error(`${ label }：${ codeList.join('、') } 已确认`);
                }
                return;
            }
            if (type === 'confirm' && list.length === 1) {
                _this.openConfirmDialog(list[0]);
                return;
            }
            _this.saveConfirmMethod(type, list);
        },
        saveConfirmMethod(type, list, dialog) {
            const _this = this;
            _this.$confirm(`是否${ type === 'confirm' ? '' : '反' }确认${ _this.type === 'sale' ? '开' : '收' }票？`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                _this.fetchData(_this.$api.API_ChangeJxcInvoiceConfirmState, {
                    sid_list: list.map(item => item.sid),
                    state: type === 'confirm' ? 1 : -1,
                }).then(() => {
                    _this.$message.success(`${ type === 'confirm' ? '确认' : '反确认' }${ _this.type === 'sale' ? '开' : '收' }票成功！`);
                    if (dialog) {
                        dialog.visible = false;
                    }
                    _this.getList();
                    _this.$bus.$emit('updateXiongdaDashboard');
                }).catch(() => {
                });
            }).catch(() => {
            });
        },
        openAuditDialog(row) {
            const _this = this;
            _this.$dialog({
                title: `审核${ _this.type === 'sale' ? '开' : '收' }票申请`,
                width: '1000px',
                component: {
                    value: InvoiceForm,
                    props: {
                        type: row.type,
                        row: row,
                        invoiceTypeList: _this.invoiceTypeList,
                        audit: true,
                    },
                },
                confirmBtn: {
                    type: 'primary',
                    text: '审核',
                    click(dialog, { component }) {
                        if (component && typeof component.confirm === 'function') {
                            component.confirm().then(data => {
                                if (data) {
                                    _this.getList();
                                    dialog.visible = false;
                                }
                            });
                        }
                    },
                },
            });
        },
        openConfirmDialog(row) {
            const _this = this;
            _this.$dialog({
                title: `确认${ _this.type === 'sale' ? '开' : '收' }票`,
                width: '1000px',
                component: {
                    value: InvoiceForm,
                    props: {
                        type: row.type,
                        row: row,
                        invoiceTypeList: _this.invoiceTypeList,
                        detail: true,
                    },
                },
                confirmBtn: {
                    type: 'success',
                    text: _this.type === 'buy' ? '确认收票' : '确认开票',
                    click(dialog) {
                        _this.saveConfirmMethod('confirm', [row], dialog);
                    },
                },
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>

</style>
